package cn.t16.ms.feign.order;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
@Transactional(readOnly = true)
public class OrderService implements IOrderService {
    @Resource
    private OrderRepository orderRepository;
    @Resource
    private OrderItemRepository orderItemRepository;


    @Override
    public Order get(Integer id) {
        return orderRepository.getOne(id);
    }

    @Override
    @Transactional
    public Order add(Order order) {
        orderRepository.save(order);
        List<OrderItem> items = order.getItems();
        items.forEach(orderItem -> {
            orderItem.setOrderId(order.getId());
            orderItemRepository.save(orderItem);
        });
        return order;
    }

    @Override
    public List<Order> getAll() {
        return orderRepository.findAll();
    }

    @Override
    public List<Order> findByUserId(Integer userId) {
        return orderRepository.findByUserId(userId);
    }
}
